package com.example.g32.paging

import android.util.Log
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.example.base.entity.NoticeEntityItem
import com.example.base.http.ApiServer
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withContext

class NoticePagingSource(val apiServer: ApiServer) : PagingSource<Int, NoticeEntityItem>() {
    override fun getRefreshKey(state: PagingState<Int, NoticeEntityItem>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, NoticeEntityItem> {
        return withContext(Dispatchers.IO) {
            try {
                var currenrtPage = params.key?:0
                val res = apiServer.getNotices(currenrtPage, 10).first()
                if (res.code == 200){
                    val nextPage=if(res.data.size==10) currenrtPage+1 else null
                    LoadResult.Page(res.data.sortedBy { it.publishTime }, null,nextPage)
                }else{
                    LoadResult.Error(Exception(res.message))
                }
            } catch (e: Exception) {
                LoadResult.Error(e)
            }
        }
    }
}